package com.itheima_01.day05;

public class ThinkZuoye {
    public static void main(String[] args) {
        int[] arr = {1, 2, 7, 2, 3, 5, 6, 7, 6, 7, 8, 8};
        int key = 7;
        int[] index = getIndex(key, arr);
        if (index == null) {
            System.out.println("没找到。。。");
        } else {
            System.out.println();
            System.out.print(key + "所对应的索引为：");
            System.out.print("[ ");
            for (int i = 0; i < index.length; i++) {
                if (i == index.length - 1) {
                    System.out.print(index[i] + " ]");
                } else {
                    System.out.print(index[i] + ", ");
                }
            }
            System.out.println();
        }
    }

    public static int[] getIndex(int key, int[] arr) {
        int count = 0;//为了方便后面创建新数组，可以知道新数组的长度
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) {
                count++;//计数，记下总共有多少个相同的数
            }
        }
        if (count == 0) {
            return null;
        }
        int[] newIndex = new int[count];//定义一个新数组接收索引对应的值
        int newInd = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) {
                newIndex[newInd] = i;//让老数组再遍历一遍，以便找到所需要的数
                newInd++;
            }
        }
        return newIndex;
    }
}
